from server import db, api_auth, user_opt
from flask import jsonify, Blueprint, request, g
from server.model.app_user import AppUser
from server.model import set_field, query_by_field
import math

r_app_user = Blueprint('app_user', __name__)


@r_app_user.route('', methods=['GET'])
@api_auth.login_required
def get_app_users():
    """
                    @@@
                    #### Args:
                           {
                                page: 1,
                                limit: 20,
                                filter: {},
                                start_time: "2021-09-10",
                                end_time: "2021-09-12",
                            }
                    #### Returns::
                            {
                                'code': 20000,
                                'items': [u.to_dict() for u in app_user_list],
                            }
                """
    page = request.args.get('page', type=int, default=1)
    limit = request.args.get('limit', type=int, default=20)
    start_time = request.args.get('start_time')
    end_time = request.args.get('end_time')
    query_filter = request.args.get('filter')
    key_word = request.args.get('key_word')

    try:

        app_user_list = AppUser.query.order_by(AppUser.id)

        if key_word:
            app_user_list = app_user_list.filter(AppUser.nick_name.like(f"%{key_word}%"))

        if query_filter:
            app_user_list = query_by_field(app_user_list, query_filter, AppUser)

        if start_time:
            app_user_list = app_user_list.filter(db.cast(AppUser.create_time, db.Date) >= start_time)

        if end_time:
            app_user_list = app_user_list.filter(db.cast(AppUser.create_time, db.Date) <= end_time)
        total = app_user_list.count()

        app_user_list = app_user_list.offset((page - 1) * limit).limit(limit).all()

        return jsonify({
            'code': 20000,
            'message': 'success',
            'items': [u.to_dict() for u in app_user_list],
            'totalCount': total,
            'TotalPageCount': math.ceil(int(total / limit))
        })
    except Exception as e:
        print("get app_users error:", e)

    return jsonify({'code': 50001, 'message': "查询app用户时发生错误"})


@r_app_user.route('', methods=['POST'])
@api_auth.login_required
def add_app_user():
    """
    @@@
    #### Args:
            {
                open_id: String(16)    #微信id
                balance: DECIMAL(11    #余额
                phone: String(16)    #手机号码
                nick_name: String(127)    #微信昵称
                status: TINYINT(unsigned=True)    #状态:0:禁用, 1:正常
            }
    #### Returns::
            {'code': 20000, 'message': "app用户添加成功"}
            {'code': 50001, 'message': "添加app用户时发生错误"}
    """

    args = request.get_json()

    app_user = AppUser()
    try:
        set_field(app_user, args)
        db.session.add(app_user)
        db.session.commit()

        user_opt.send({
            "operation": "添加app用户",
            "method": "app用户管理",
            "params": app_user.id,
            "user_id": g.user.id,
            "username": g.user.username
        })

        return jsonify({'code': 20000, 'message': "app用户添加成功"})
    except Exception as e:
        db.session.rollback()
        print("add app_user error:", e)

    return jsonify({'code': 50001, 'message': "添加app用户时发生错误"})


@r_app_user.route('/<int:pid>', methods=['DELETE'])
@api_auth.login_required
def remove_app_user(pid):
    """
        @@@
        #### Args:
                app_user/id
        #### Returns::
                {'code': 20000, 'message': "app用户删除成功"}
                {'code': 50001, 'message': "删除app用户时发生错误"}
        """
    try:
        AppUser.query.filter_by(id=pid).delete()
        db.session.commit()

        user_opt.send({
            "operation": "删除app用户",
            "method": "app用户管理",
            "params": pid,
            "user_id": g.user.id,
            "username": g.user.username
        })

        return jsonify({'code': 20000, 'message': "app用户删除成功"})
    except Exception as e:
        print("remove app_user error:", e)
        return jsonify({
            'code': 50001,
            'message': "删除app用户时发生错误"
        })


@r_app_user.route('/<int:pid>', methods=['PUT'])
@api_auth.login_required
def edit_app_user(pid):
    """
    @@@
    #### Args:
           app_user/id
    #### Returns::
            {'code': 20000, 'message': "app用户修改成功"}
            {'code': 50001, 'message': "修改app用户时发生错误"}
    """
    args = request.get_json()
    try:
        app_user = AppUser.query.filter_by(id=pid).first()
        set_field(app_user, args)

        db.session.commit()

        user_opt.send({
            "operation": "修改app用户",
            "method": "app用户管理",
            "params": pid,
            "user_id": g.user.id,
            "username": g.user.username
        })

        return jsonify({'code': 20000, 'message': "app用户修改成功"})
    except Exception as e:
        db.session.rollback()
        print("edit app_user error:", e)

    return jsonify({'code': 50001, 'message': "修改app用户时发生错误"})


@r_app_user.route('/<int:pid>', methods=['GET'])
@api_auth.login_required
def get_detail(pid):
    """
                    @@@
                    #### Args:
                           app_user/id
                    #### Returns::
                            {
                                'code': 20000,
                                'items': [u.to_dict() for u in app_user_list],
                            }
                """
    app_user = AppUser.query.filter_by(id=pid).first()
    if not app_user:
        return jsonify({
            'code': 50002,
            'message': '查询app用户不存在'
        })

    return jsonify({
        'code': 20000,
        'message': 'success',
        'items': app_user.to_dict(),
    })

# >>>>> auto generate end <<<<<
